#!/bin/bash
set -e

MYSQL_TAR="mysql-8.0.25-linux-glibc2.12-x86_64.tar.xz"
MYSQL_DIR="/usr/local/mysql"
MYSQL_USER="mysql"
DATA_DIR="$MYSQL_DIR/data"

echo "==> 检查 mysql 用户..."
id $MYSQL_USER &>/dev/null || useradd -r -s /sbin/nologin $MYSQL_USER

echo "==> 解压 MySQL 安装包..."
tar -xf $MYSQL_TAR -C /usr/local/
mv /usr/local/mysql-8.0.25-linux-glibc2.12-x86_64 $MYSQL_DIR

echo "==> 创建数据目录并授权..."
mkdir -p $DATA_DIR
chown -R $MYSQL_USER:$MYSQL_USER $MYSQL_DIR

echo "==> 初始化 MySQL（无密码）..."
$MYSQL_DIR/bin/mysqld --initialize-insecure --user=$MYSQL_USER --basedir=$MYSQL_DIR --datadir=$DATA_DIR

echo "==> 配置环境变量..."
echo "export PATH=$MYSQL_DIR/bin:\$PATH" > /etc/profile.d/mysql.sh
chmod +x /etc/profile.d/mysql.sh
source /etc/profile.d/mysql.sh

echo "==> 创建 systemd 服务..."
cat >/etc/systemd/system/mysqld.service <<EOF
[Unit]
Description=MySQL Server
After=network.target

[Service]
User=$MYSQL_USER
Group=$MYSQL_USER
ExecStart=$MYSQL_DIR/bin/mysqld_safe --datadir=$DATA_DIR
LimitNOFILE=5000
Restart=on-failure
TimeoutSec=300

[Install]
WantedBy=multi-user.target
EOF

echo "==> 启动并设置开机自启..."
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable mysqld
systemctl start mysqld

echo
echo "✅ MySQL 8.0.25 已成功安装并启动！"
echo "👉 默认 root 无密码，可使用以下命令登录并设置密码："
echo "   mysql -u root"
echo "   ALTER USER 'root'@'localhost' IDENTIFIED BY '新密码';"
